package curves;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import function.FunVariations;
import function.Function;
import function.Functions;
import function.SyntaxErrorException;

public class PanelCalcul extends JPanel{
	
	private static final long serialVersionUID = 1L;
	public JLabel y;
	
	public PanelCalcul(final FunctionVariations var){
		super();
		
		//var.fun(1);
		
		this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		this.setBorder(new EtchedBorder());
		
//		 ---- CHAMPS FONCTION -----
		JPanel fonction = new JPanel();
		final JTextField textField = new JTextField(20);
		textField.addActionListener(new ActionListener(){
			 public void actionPerformed(ActionEvent evt) {
			        //System.out.println(textField.getText());
			        //textField.selectAll();
				 	Function fun = null;
				 	try{
				 		fun = Functions.parse(textField.getText());
				 		FunctionVariations fvar = (FunctionVariations)new FunVariations(fun, var.getXmin(), var.getXmax());
				 		fvar.tabulate(1);
				 		new CurveFrame(fvar);
				 	} catch (SyntaxErrorException e){
				 		textField.selectAll();
				 	} catch (IOException e){
				 		e.printStackTrace();
				 	}
			    }
		});
		fonction.add(new JLabel("Fonction :\n"));
		fonction.add(textField);
		this.add(fonction);
//		 ---- CHAMPS FONCTION ----
		
		
//		 ---- CHAMPS CALCUL ----
		JPanel calculX = new JPanel();
		calculX.setLayout(new FlowLayout());
		JLabel labelX = new JLabel("Calcul de Y pour X =");
		JLabel labelY = new JLabel("=> Y = ");
		JTextField textX = new JTextField(4);
		y = new JLabel();
		CaretListener updateY = new CaretListener(){
				public void caretUpdate(CaretEvent e) {
					JTextField text = (JTextField)e.getSource();
					double xvar;
					try {
						xvar = Double.parseDouble(text.getText());
					} catch(NumberFormatException e2){
						xvar = 0.0;
					}
					
					FunVariations fvar = (FunVariations)var;
					y.setText(Double.toString(fvar.fun(xvar)));
				}
			};
		textX.addCaretListener(updateY);
	
		calculX.add(labelX);
		calculX.add(textX);
		calculX.add(labelY);
		calculX.add(y);
		this.add(calculX);
//		 ---- CHAMPS CALCUL ----
	}

}
